#!/usr/bin/env bash

source ../../lib/shell/env.sh
source ./network_stress.sh

# # # # # # # # main # # # # # # # #
stress_network_env 5 $(echo "($RUNTIME - 5*30) / 5"|bc)
IPERF3_INTERVAL=0

get_available_interface "false"|| { echo "Fialed to get available interface!";exit 1; }
start_time=$(date +%s -d "$(date "+%F %H:%M:%S")")
cpu_nums=$(lscpu|grep -e "^CPU(s):"|awk '{print $NF}')
[ "$(echo "$cpu_nums >= 10"|bc)" -eq 1 ] && default_proc_nums=10 || default_proc_nums=$(echo "`seq 10`"|xargs -n1 -I@ bash -c "[ \`echo \"$cpu_nums>=@\"|bc\` -eq 1 ] && echo @ && exit"|shuf -n1)
default_port=$IPERF3_PORT
for ((i=1;i<=5;i++));do
    cur_err_msg=""
    cur_time=$(date +%s -d "$(date "+%F %H:%M:%S")")

    #TCP and UDP concurrency
    IPERF3_PORT=$default_port
    for info in {TCP:$default_proc_nums,UDP:$default_proc_nums,TCP:$cpu_nums,UDP:$cpu_nums};do
        ((IPERF3_PORT+=50))
        IPERF3_CONNECT_MODE="${info%%:*}"
        IPERF3_PROCESS_NUM="${info##*:}"
        IPERF3_LOG=""
        echo -e "\n##########[Network $IPERF3_CONNECT_MODE, concurrent $IPERF3_PROCESS_NUM, port $IPERF3_PORT,  for network stress test--->$i]##########"
        run_iperf3_stress_test "${IPERF3_LOG_PATH}/${IPERF3_CONNECT_MODE,,}_${IPERF3_PROCESS_NUM}_${IPERF3_PORT}.log" &
        sleep 1
    done
    wait
    sleep 6
    #check iperf3 stress results
    IPERF3_PORT=$default_port
    for info in {TCP:$default_proc_nums,UDP:$default_proc_nums,TCP:$cpu_nums,UDP:$cpu_nums};do
        ((IPERF3_PORT+=50))
        IPERF3_CONNECT_MODE="${info%%:*}"
        IPERF3_PROCESS_NUM="${info##*:}"
        if ! check_iperf3_stress_results "${IPERF3_LOG_PATH}/${IPERF3_CONNECT_MODE,,}_${IPERF3_PROCESS_NUM}_${IPERF3_PORT}.log";then
            cur_err_msg="${cur_err_msg}${IPERF3_CONNECT_MODE} connection, ${IPERF3_PROCESS_NUM} process, port $IPERF3_PORT, Network stress test failure.\n"
        fi
    done
    [ -n "$cur_err_msg" ] && { echo -e "$cur_err_msg";test_fail; }
    cur_time_diff=$(($(date +%s -d "$(date "+%F %H:%M:%S")") - $cur_time))
    [ $(($(date +%s -d "$(date "+%F %H:%M:%S")") - $start_time + 2 * $cur_time_diff)) -ge $RUNTIME ] && break
done
trap "sh ./../../../utils/sshconf.sh restore" EXIT
test_pass
